import { useWebSocket } from '@vueuse/core'
import type { DeviceName, DeviceResponseMap } from '@/types/ws'

type UseDeviceWebsocketOptions<T extends DeviceName> = {
  deviceName: T
  onMessage?: (data: DeviceResponseMap[T]) => void
  connectOnMount?: boolean
  disConnectOnDestroy?: boolean
}

export const useDeviceWebsocket = <T extends DeviceName>(
  targetUrl: string,
  options: UseDeviceWebsocketOptions<T>,
) => {
  const onConnected = () => {
    console.log(`${targetUrl} 连接成功`)
  }

  const onDisconnected = (ws: WebSocket, event: CloseEvent) => {
    console.log(`${targetUrl} 连接关闭`, event)
  }

  const onError = (ws: WebSocket, event: Event) => {
    console.info(`${targetUrl} 连接失败：`, event)
  }

  const onMessage = (ws: WebSocket, event: MessageEvent) => {
    console.log(`${targetUrl} 接收消息：`, event)
    try {
      const response = JSON.parse(event.data) as DeviceResponseMap[T]
      if (options && options.onMessage) {
        options.onMessage(response)
      }
    } catch (e) {
      console.error(`${targetUrl} 返回非JSON文本消息，错误信息：`, e)
    }
  }

  const { send, close, open, status } = useWebSocket(targetUrl, {
    onConnected,
    onDisconnected,
    onError,
    onMessage,
    autoReconnect: {
      retries: 5,
      delay: 10 * 1000,
      onFailed: () => {
        ElMessage.error(`${targetUrl} 连接重试失败，请检查网络或服务器状态`)
      },
    },
    immediate: !!options.connectOnMount,
  })

  return {
    status,
    send,
    open,
    close,
  }
}
